from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import os
import urllib
import urllib2
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.ext import db


class Card(db.Model):
  author = db.UserProperty()
  front = db.StringProperty(multiline=True)
  back = db.StringProperty(multiline=True)
  url = db.StringProperty(multiline=False)


class MainPage(webapp.RequestHandler):
  def get(self):
    url = self.request.get("url")
    #url = "http://en.wikipedia.org/wiki/DevHouse"
    result = urlfetch.fetch(url)
    #self.response.headers['Content-Type'] = 'text/html'
    #self.response.out.write(result.content)
    
    cards = db.GqlQuery("SELECT * FROM Card")

    cardout = '<div id="card_set">'
    for card in cards:
      cardout = cardout + '<div class="card_icon">'
      ss = ''
      if (len(card.front) > 50):
        ss = card.front[0:50]
      else:
        ss = card.front
      cardout += ss
      cardout += '<span class="hidspan front">' + card.front + '</span>'
      cardout += '<span class="hidspan back">' + card.back + '</span></div>'
    
    cardout = cardout + '</div>' 

    template_values = {
      'pagecontent': result.content,
      'url': url,
      'cardout': cardout,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class SaveCard(webapp.RequestHandler):
  def post(self):
    card = Card();
    if users.get_current_user():
      card.author = users.get_current_user()
    
    front = self.request.get("card_front")
    card.front = front
    back = self.request.get("card_back")
    card.back = back
    url = self.request.get("url")
    card.url = url
    card.put()
    self.redirect('/?url=' + url)
    
    
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/savecard',SaveCard)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
